package com.dbh.alg.datastructure;

/**
 * 删除排序链表中重复元素
 * @author dongbanghui
 * @date 2025/5/9
 */
public class E05Leetcode82 {

    public static ListNode deleteDuplicates(ListNode p) {
        if (p == null || p.next == null) {
            return p;
        }
        if (p.val == p.next.val) {
            ListNode x = p.next.next;
            while (x != null && x.val == p.val) {
                x = x.next;
            }
            return deleteDuplicates(x);
        } else {
            p.next = deleteDuplicates(p.next);
            return p;
        }
    }

    public static ListNode deleteDuplicates2(ListNode p) {
        if (p == null || p.next == null) {
            return p;
        }
        ListNode s = new ListNode(-1, p);
        ListNode p1 = s;
        ListNode p2, p3;
        while((p2 = p1.next) != null && (p3 = p2.next) != null) {
            if (p2.val == p3.val) {
                while((p3 = p3.next) != null && p2.val == p3.val) {
                }
                // 找不到重复值
                p1.next = p3;
            } else {
                p1 = p1.next;
            }
        }
        return s.next;
    }

    public static void main(String[] args) {
        ListNode o = ListNode.of(1, 2, 3, 3, 4, 4, 5);
        System.out.println(deleteDuplicates2(o));
    }

}
